<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form size="small" :inline="true" @submit.native.prevent>
      <el-form-item label="设备编号">
        <el-select
          v-model="searchForm.deviceCode"
          placeholder="请选择"
          filterable
        >
          <el-option
            v-for="item in deviceNos"
            :key="item.value"
            :label="item.label1"
            :value="item.value"
          >
            <span style="float: left">{{ item.label1 }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{
              item.label2
            }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="区分">
        <el-select
          v-model="searchForm.type"
          placeholder="请选择"
          filterable
          clearable
        >
          <el-option
            v-for="item in types"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="值" prop="value">
        <el-input
          v-model="searchForm.value"
          placeholder="请输入"
          clearable
          @keyup.enter.native="getInfo"
        />
      </el-form-item>
      <!-- <el-form-item label="处置时间">
        <el-date-picker
          value-format="yyyy-MM-dd"
          v-model="searchForm.handleDate"
          type="daterange"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="mini"
          style="width: 200px"
        >
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          size="mini"
          @click="handleSearch('搜索')"
          class="button"
          plain
          >搜索</el-button
        >
        <el-button
          type="info"
          size="mini"
          @click="handleReset('0')"
          class="button"
          plain
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain size="mini" @click="handleDowload()"
          >导出</el-button
        >
      </el-col>
    </el-row>
    <!-- 表 -->
    <el-table
      v-loading="loading"
      :data="tableList"
      border
      :max-height="THeight"
    >
      <el-table-column label="序号" align="center" prop="Index" width="50" />
      <el-table-column label="设备编号" align="center" prop="deviceCode" />
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="线别名称" align="center" prop="lineId" />
      <el-table-column label="所属课别" align="center" prop="dept" />
      <el-table-column label="值" align="center" prop="value" />
      <el-table-column label="异常项目" align="center" prop="project" />
      <el-table-column label="异常原因" align="center" prop="reason" />
      <el-table-column
        label="发生时间"
        align="center"
        prop="dateTime"
        width="145"
      />
      <el-table-column label="处置详情" align="center">
        <el-table-column label="解锁工号" align="center" prop="user" />
        <el-table-column label="解锁姓名" align="center" prop="userName" />
        <el-table-column label="解锁部门" align="center" prop="userDept" />
        <el-table-column label="处置类型" align="center" prop="actionType1" />
        <el-table-column label="处置方式" align="center" prop="actionType2" />
        <el-table-column
          label="处置时间"
          align="center"
          prop="actionTime"
          width="145"
        />
      </el-table-column>
      <el-table-column label="FACA状态" align="center" prop="facaState"
        ><template slot-scope="scope">
          <el-tag
            :type="scope.row.facaState === 1 ? 'success' : 'info'"
            disable-transitions
            >{{ scope.row.facaState == 1 ? "完成" : "未完成" }}</el-tag
          >
        </template></el-table-column
      >
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleFACA(scope.row)"
            >FACA</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <pagination
      :total="total"
      :page.sync="Page.pageNum"
      :limit.sync="Page.pageSize"
      @pagination="getInfo()"
    />
    <!-- FACA dialog -->
    <el-dialog
      title="FACA"
      :visible.sync="FACAOpen"
      width="750px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="dialogCancel"
    >
      <el-card>
        <el-row :gutter="10" class="mb8" v-if="showSave">
          <el-col :span="1.5">
            <el-button type="success" size="mini" @click="addRow(1)" plain
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              size="mini"
              @click="delRow"
              plain
              :disabled="multiple"
              >删除</el-button
            >
          </el-col>
        </el-row>
        <el-table
          ref="refTable"
          :data="FACAData"
          border
          max-height="600"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" fixed />
          <el-table-column
            label="序号"
            align="center"
            type="index"
            width="50"
          />
          <el-table-column label="原因" align="center" prop="question">
            <template slot-scope="scope">
              <el-input
                type="textarea"
                rows="2"
                placeholder="请输入"
                v-model="scope.row.question"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="对策" align="center" prop="answer">
            <template slot-scope="scope">
              <el-input
                type="textarea"
                rows="2"
                placeholder="请输入"
                v-model="scope.row.answer"
              ></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="info" plain size="mini" @click="dialogCancel"
          >取 消</el-button
        > -->
        <el-button
          type="warning"
          plain
          size="mini"
          @click="dialogSubmit1"
          v-if="showSave"
          >保 存</el-button
        >
        <el-button
          type="success"
          plain
          size="mini"
          @click="dialogSubmit2"
          v-if="showSave"
          ><span>完成</span><br /><span>(邮件通知“FACA课长”)</span></el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import ErrorDataMixins from "./errorDataMixins";
import {
  UpdateFACA,
  reqGetResult,
  reqEnterReView,
  reqSendEMail,
} from "@/api/newApi/OCAP/index.js";
import XLSX from "xlsx";
import moment from "moment";
export default {
  mixins: [ErrorDataMixins],
  data() {
    return {
      searchForm: { state: 0 }, //0已处置
      //FACA弹框
      FACAOpen: false,
      FACAData: [],
      defaultData: { id: null, question: null, answer: null },
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      //当前行id
      resultId: null,
      showSave: false,
      deviceCode: null,
    };
  },
  computed: {
    ...mapGetters(["account"]),
  },
  mounted() {
    let query = this.$route.query;
    this.searchForm = { ...this.searchForm, ...query };
    console.log(query);
  },
  methods: {
    //填写FACA
    handleFACA(row) {
      this.deviceCode = row.deviceCode;
      this.showSave = row.facaState == 1 ? false : true;
      this.resultId = row.resultId;
      if (row.listFACA.length > 0) {
        this.addRow(row.listFACA.length, row.listFACA);
      } else {
        this.addRow(5);
      }
      this.FACAOpen = true;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id).sort((a, b) => b - a);
      this.single = selection.length != 1; // 非单个禁用
      this.multiple = !selection.length; // 非多个禁用
    },
    //添加行
    addRow(num, data) {
      if (data != undefined) {
        this.FACAData = [];
        data.forEach((item, index) => {
          this.FACAData.push({
            id: this.FACAData.length,
            question: item.question,
            answer: item.answer,
          });
        });
      } else {
        let Num = 5;
        if (num) {
          Num = num;
        }
        //默认5行
        for (let i = 0; i < Num; i++) {
          this.FACAData.push({
            ...this.defaultData,
            id: this.FACAData.length,
          });
        }
      }
      //滚动条默认拉至表格最底下
      this.$nextTick(() => {
        let scrollHeight = this.$refs.refTable.bodyWrapper.scrollHeight;
        this.$refs.refTable.bodyWrapper.scrollTop = scrollHeight;
      });
    },
    //删除行
    delRow() {
      let Indexs = this.ids.map((item) => {
        return item + 1;
      });
      this.$modal
        .confirm(
          '是否确认删除序号为"' + Indexs.sort((a, b) => a - b) + '"的数据项？'
        )
        .then(() => {
          //删除
          this.FACAData = this.FACAData.filter((item, index) => {
            return !this.ids.includes(item.id);
          });
          //重新排序
          this.FACAData.forEach((item, index) => {
            item.id = index;
          });
          //重新赋值
          this.FACAData = [...this.FACAData];
        })
        .catch(() => {});
    },
    dialogCancel() {
      this.FACAData = [];
      this.FACAOpen = false;
    },
    async dialogSubmit1() {
      //删除this.FACAData中answer和question为null或""的对象
      let ids = [];
      let reqFACAData = [];
      this.FACAData.forEach((item) => {
        if (!item.answer && !item.question) {
          ids.push(item.id);
        }
      });
      //删除this.FACAData中id在ids中的对象
      reqFACAData = this.FACAData.filter((item) => {
        return !ids.includes(item.id);
      });
      //重新排序
      reqFACAData.forEach((item, index) => {
        item.id = index;
      });
      let res = await UpdateFACA({
        id: this.resultId,
        listFACA: reqFACAData,
      });
      if (res.code == 0) {
        this.$modal.msgSuccess("已保存");
        this.getInfo();
      } else {
        this.$modal.msgError(res.msg);
      }
      this.FACAOpen = false;
    },
    async dialogSubmit2() {
      //删除this.FACAData中answer和question为null或""的对象
      let ids = [];
      let reqFACAData = [];
      this.FACAData.forEach((item) => {
        if (!item.answer && !item.question) {
          ids.push(item.id);
        }
      });
      //删除this.FACAData中id在ids中的对象
      reqFACAData = this.FACAData.filter((item) => {
        return !ids.includes(item.id);
      });
      //重新排序
      reqFACAData.forEach((item, index) => {
        item.id = index;
      });
      this.loading = true;
      let res = await UpdateFACA({
        id: this.resultId,
        listFACA: reqFACAData,
      });
      if (res.code != 0) {
        this.$modal.msgError(res.msg);
      } else {
        //转到审批
        let res1 = await reqEnterReView({
          deviceCode: this.deviceCode,
          userId: this.account,
          resultId: this.resultId.toString(),
        });
        if (res1.code == 0) {
          this.FACAOpen = false;
          let res2 = await reqSendEMail({
            deviceCode: this.deviceCode,
            resultId: this.resultId,
            NextStepName: "FACA2",
            NextStepNameZh: "FACA课长",
          });
          if (res2.code == 200) {
            this.$modal.msgSuccess("邮件已发送给FACA课长");
          } else {
            this.$modal.msgWarning(res2.msg);
          }
          this.loading = false;
          this.getInfo();
        } else {
          this.$modal.msgError(res1.msg);
        }
      }
    },
    //导出
    async handleDowload() {
      let reqForm = Object.assign(
        { user: this.userInfo.user },
        this.searchForm,
        {
          pageNum: 0,
          pageSize: 0,
        }
      );
      reqForm.deviceCode = this.searchForm.deviceCode
        ? this.searchForm.deviceCode.split("拼接")[0]
        : null;
      let res = await reqGetResult(reqForm);
      if (res.code == 0) {
        try {
          this.$modal.msgSuccess("正在下载，请稍等");
          let header = [
            "序号",
            "设备编号",
            "值",
            "异常项目",
            "异常原因",
            "发生时间",
            "解锁工号",
            "处置类型",
            "处置方式",
            "处置时间",
            "FACA状态",
            "FACA",
          ];
          const datas = res.data.map((item, index) => [
            index + 1,
            item.deviceCode,
            item.value,
            item.project,
            item.reason,
            item.dateTime,
            item.user,
            item.actionType1,
            item.actionType2,
            item.actionTime,
            (() => {
              return parseInt(item.facaState) == 1 ? "完成" : "未完成";
            })(),
            (() => {
              let arr = [];
              if (item.listFACA.length > 0) {
                item.listFACA.forEach((item2) => {
                  arr.push({ 原因: item2.question, 对策: item2.answer });
                });
              }
              return item.listFACA.length > 0 ? JSON.stringify(arr) : "无";
            })(),
          ]);
          let Data = [header, ...datas];
          const worksheet = XLSX.utils.aoa_to_sheet(Data);
          const workbook = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(workbook, worksheet, "sheet1");
          XLSX.writeFile(
            workbook,
            `异常处置历史数据${moment(new Date()).format(
              "yyyy-MM-DD HH:mm"
            )}.xlsx`
          );
        } catch (err) {
          this.$modal.msgError(err);
        }
      } else {
        this.$modal.msgError(res.message);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
/* //表头颜色 */
::v-deep .el-table .el-table__header-wrapper th,
.el-table .el-table__fixed-header-wrapper th {
  background-color: #f0f8ff !important;
}

/* dialog */
::v-deep .el-dialog__body {
  padding: 0 20px 10px 20px;
}

::v-deep .el-card__body {
  padding: 10px 10px 10px 10px;
}
</style>